/**
 * Copyright (c) www.longdw.com
 */
package com.ldw.music.lrc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import android.content.Context;
import android.util.Log;

import com.ldw.music.MusicApp;

/**
 * 姝岃瘝涓嬭浇
 * @author longdw(longdawei1988@gmail.com)
 *
 */
public class LyricDownloadManager {
	private static final String TAG = LyricDownloadManager.class
			.getSimpleName();
	public static final String GB2312 = "GB2312";
	public static final String UTF_8 = "utf-8";
	private final int mTimeOut = 10 * 1000;
	private LyricXMLParser mLyricXMLParser = new LyricXMLParser();
	private URL mUrl = null;
	private int mDownloadLyricId = -1;

//	private Context mContext = null;

	public LyricDownloadManager(Context c) {
//		mContext = c;
	}

	/*
	 * 鏍规嵁姝屾洸鍚嶅拰姝屾墜鍚嶅彇寰楄姝岀殑XML淇℃伅鏂囦欢 杩斿洖姝岃瘝淇濆瓨璺緞
	 */
	public String searchLyricFromWeb(String musicName, String singerName, String oldMusicName) {
		Log.i(TAG, "涓嬭浇鍓嶏紝姝屾洸鍚�" + musicName + ",姝屾墜鍚�" + singerName);

		// 浼犺繘鏉ョ殑濡傛灉鏄眽瀛楋紝閭ｄ箞灏辫杩涜缂栫爜杞寲
		try {
			musicName = URLEncoder.encode(musicName, UTF_8);
			singerName = URLEncoder.encode(singerName, UTF_8);
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}

		// 鐧惧害闊充箰鐩掔殑API
		String strUrl = "http://box.zhangmen.baidu.com/x?op=12&count=1&title="
				+ musicName + "$$" + singerName + "$$$$";

		// 鐢熸垚URL
		try {
			mUrl = new URL(strUrl);
			Log.i(TAG, "璇锋眰鑾峰彇姝岃瘝淇℃伅鐨刄RL锛� + mUrl);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		try {
			HttpURLConnection httpConn = (HttpURLConnection) mUrl
					.openConnection();
			httpConn.setReadTimeout(mTimeOut);
			if (httpConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				Log.i(TAG, "http杩炴帴澶辫触");
				return null;
			}
			httpConn.connect();
			Log.i(TAG, "http杩炴帴鎴愬姛");

			// 灏嗙櫨搴﹂煶涔愮洅鐨勮繑鍥炵殑杈撳叆娴佷紶閫掔粰鑷畾涔夌殑XML瑙ｆ瀽鍣紝瑙ｆ瀽鍑烘瓕璇嶇殑涓嬭浇ID
			mDownloadLyricId = mLyricXMLParser.parseLyricId(httpConn
					.getInputStream());
			httpConn.disconnect();
		} catch (IOException e1) {
			e1.printStackTrace();
			Log.i(TAG, "http杩炴帴杩炴帴IO寮傚父");
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			Log.i(TAG, "XML瑙ｆ瀽閿欒");
			return null;
		}
		return fetchLyricContent(musicName, singerName, oldMusicName);
	}

	/** 鏍规嵁姝岃瘝涓嬭浇ID锛岃幏鍙栫綉缁滀笂鐨勬瓕璇嶆枃鏈唴瀹�
	 * @param musicInfo */
	private String fetchLyricContent(String musicName, String singerName, String oldMusicName) {
		if (mDownloadLyricId == -1) {
			Log.i(TAG, "鏈寚瀹氭瓕璇嶄笅杞絀D");
			return null;
		}
		BufferedReader br = null;
		StringBuilder content = null;
		String temp = null;
		String lyricURL = "http://box.zhangmen.baidu.com/bdlrc/"
				+ mDownloadLyricId / 100 + "/" + mDownloadLyricId + ".lrc";
		Log.i(TAG, "姝岃瘝鐨勭湡瀹炰笅杞藉湴鍧�" + lyricURL);

		try {
			mUrl = new URL(lyricURL);
		} catch (MalformedURLException e2) {
			e2.printStackTrace();
		}

		// 鑾峰彇姝岃瘝鏂囨湰锛屽瓨鍦ㄥ瓧绗︿覆绫讳腑
		try {
			// 寤虹珛缃戠粶杩炴帴
			br = new BufferedReader(new InputStreamReader(mUrl.openStream(),
					GB2312));
			if (br != null) {
				content = new StringBuilder();
				// 閫愯鑾峰彇姝岃瘝鏂囨湰
				while ((temp = br.readLine()) != null) {
					content.append(temp);
					Log.i(TAG, "<Lyric>" + temp);
				}
				br.close();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
			Log.i(TAG, "姝岃瘝鑾峰彇澶辫触");
		}

		try {
			musicName = URLDecoder.decode(musicName, UTF_8);
			singerName = URLDecoder.decode(singerName, UTF_8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (content != null) {
			// 妫�煡淇濆瓨鐨勭洰褰曟槸鍚﹀凡缁忓垱寤�
//			String folderPath = PreferenceManager.getDefaultSharedPreferences(
//					mContext).getString(SettingFragment.KEY_LYRIC_SAVE_PATH,
//					Constant.LYRIC_SAVE_FOLDER_PATH);
			String folderPath = MusicApp.lrcPath;

			File savefolder = new File(folderPath);
			if (!savefolder.exists()) {
				savefolder.mkdirs();
			}
			String savePath = folderPath + File.separator + oldMusicName
					+ ".lrc";
//			String savePath = folderPath + File.separator + musicName + ".lrc";
			Log.i(TAG, "姝岃瘝淇濆瓨璺緞:" + savePath);

			saveLyric(content.toString(), savePath);

			return savePath;
		} else {
			return null;
		}

	}

	/** 灏嗘瓕璇嶄繚瀛樺埌鏈湴锛屽啓鍏ュ瀛樹腑 */
	private void saveLyric(String content, String filePath) {
		// 淇濆瓨鍒版湰鍦�		File file = new File(filePath);
		try {
			OutputStream outstream = new FileOutputStream(file);
			OutputStreamWriter out = new OutputStreamWriter(outstream);
			out.write(content);
			out.close();
		} catch (java.io.IOException e) {
			e.printStackTrace();
			Log.i(TAG, "寰堥仐鎲撅紝灏嗘瓕璇嶅啓鍏ュ瀛樻椂鍙戠敓浜咺O閿欒");
		}
		Log.i(TAG, "姝岃瘝淇濆瓨鎴愬姛");
	}
}